import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Flutter与Android通信示例')),
        body: const CommunicationExample(),
      ),
    );
  }
}

class CommunicationExample extends StatefulWidget {
  const CommunicationExample({Key? key}) : super(key: key);

  @override
  State<CommunicationExample> createState() => _CommunicationExampleState();
}

class _CommunicationExampleState extends State<CommunicationExample> {
  static const platform = MethodChannel('samples.flutter.dev/battery');
  static const eventChannel = EventChannel('samples.flutter.dev/charging');

  String _batteryLevel = '电池电量未知';
  String _chargingStatus = '充电状态未知';

  // 调用Android方法获取电池电量
  Future<void> _getBatteryLevel() async {
    String batteryLevel;
    try {
      final int result = await platform.invokeMethod('getBatteryLevel');
      batteryLevel = '电池电量: $result%';
    } on PlatformException catch (e) {
      batteryLevel = "获取电池电量失败: '${e.message}'.";
    }

    setState(() {
      _batteryLevel = batteryLevel;
    });
  }

  // 注册监听Android发送的充电状态变化
  @override
  void initState() {
    super.initState();
    eventChannel.receiveBroadcastStream().listen(_onEvent, onError:_onError);
  }

  void _onEvent(Object? event) {
    setState(() {
      _chargingStatus = "充电状态: ${event.toString()}";
    });
  }

  void _onError(Object error) {
    setState(() {
      _chargingStatus = '充电状态错误: ${error.toString()}';
    });
  }

  // 向Android发送消息
  Future<void> _sendMessageToAndroid() async {
    try {
      // 通过BasicMessageChannel发送消息
      const messageChannel = BasicMessageChannel(
        'samples.flutter.dev/message',
        StringCodec(),
      );

      final String reply = await messageChannel.send('来自Flutter的消息: 你好Android!') ?? '无回复';
      print('收到Android回复: $reply');
    } catch (e) {
      print('发送消息失败: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          ElevatedButton(
            onPressed: _getBatteryLevel,
            child: const Text('获取电池电量'),
          ),
          Text(_batteryLevel),
          Text(_chargingStatus),
          ElevatedButton(
            onPressed: _sendMessageToAndroid,
            child: const Text('发送消息到Android'),
          ),
          // 用于接收Android主动调用的方法
          ElevatedButton(
            onPressed: () {
              platform.invokeMethod('showToast', '来自Flutter的Toast');
            },
            child: const Text('显示Toast'),
          ),
        ],
      ),
    );
  }
}